#!/bin/sh
# 1. pull docker images we need
workdir=$PWD
echo "current work dirctory: $workdir"

echo 'pull images begin...'

image_array=("nginx:latest" "php:7.4-fpm" "mysql:8.0" "redis:latest")
for image in ${image_array[@]};
do
	docker images | grep -E ${image/:/\.\*} &> /dev/null
    if [ $? -ne 0 ]
    then
        echo "pull $image image begin..."
        docker pull $image
        echo "pull $image image done"
    else
        echo "$image image is existed!!!"
    fi
done

echo 'pull images done'

# 2. get config files
dir_array=("etc" "log" "data" "html")
for dir in ${dir_array[@]};
do
	if [ ! -d $dir ]; then
        mkdir $dir
    fi
done

# nginx
docker run --name tmp-nginx -d nginx # contaner for tempary
docker cp tmp-nginx:/etc/nginx ./etc/nginx # copy files of container into the directory of localhost
docker cp tmp-nginx:/var/log/nginx ./log/nginx
docker cp tmp-nginx:/usr/share/nginx/html . # copy html directory to ./html directory
docker rm -f tmp-nginx # remove container after copying

# php-fpm
docker run --name tmp-php-fpm -d php:7.4-fpm
docker cp tmp-php-fpm:/usr/local/etc ./etc/php
docker rm -f tmp-php-fpm
# copy config file 
mv ./etc/php/php/php.ini-development ./etc/php/php/php.ini
# create simple test files of php
cd ./html
rm -rf index.php phpinfo.php
touch index.php phpinfo.php
echo "<?php echo 'hello php'; " >> index.php
echo "<?php phpinfo(); " >> phpinfo.php
cp ../install-php-extensions.sh .
cd ..

cd ./etc/php/php/conf.d
rm -rf docker-php-ext-pdo_mysql.ini docker-php-ext-redis.ini
touch docker-php-ext-pdo_mysql.ini && echo "extension=pdo_mysql.so" >> docker-php-ext-pdo_mysql.ini
touch docker-php-ext-redis.ini && echo "extension=redis.so" >> docker-php-ext-redis.ini

# mysql
cd $workdir
docker run --name tmp-mysql -d mysql:8.0
docker cp tmp-mysql:/etc/mysql/conf.d ./etc/mysql
docker cp tmp-mysql:/var/log ./log/mysql
docker cp tmp-mysql:/var/lib/mysql ./data/mysql
docker rm -f tmp-mysql

# redis
# TBD

# create network bridge
docker network ls | grep lnmp &> /dev/null
if [ $? -ne 0 ]
then
    echo "network lnmp create begin..."
    docker network create lnmp
    echo "network lnmp create done"
else
    echo "network lnmp is existed!!!"
fi
